﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;
using System.Windows.Controls;

namespace Goldlight.Mvvm.Base.Behaviors
{
    /// <summary>
    /// 
    /// </summary>
    public class TextboxDragDropBehavior 
    {
        /// <summary>
        /// Dependency property to register the click command.
        /// </summary>
        public static DependencyProperty DragDropProperty =
            DependencyProperty.RegisterAttached("DragDrop", typeof(DataFormat), typeof(TextboxDragDropBehavior),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback(DragDropChanged)));

        public static void SetDragDrop(DependencyObject target, DataFormat value)
        {
            target.SetValue(DragDropProperty, value);
        }

        public static DataFormat GetDragDrop(DependencyObject target)
        {
            return (DataFormat)target.GetValue(DragDropProperty);
        }

        /// <summary>
        /// Handle the click changed event.
        /// </summary>
        private static void DragDropChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            UIElement element = target as UIElement;

            if (element != null)
            {
                if (e.NewValue != null && e.OldValue == null)
                {
                    element.PreviewDragEnter += new System.Windows.DragEventHandler(element_PreviewDragEnter);
                    element.PreviewDragOver += new System.Windows.DragEventHandler(element_PreviewDragEnter);
                    element.PreviewDrop += new System.Windows.DragEventHandler(element_PreviewDrop);
                }
                else if (e.NewValue == null && e.OldValue != null)
                {
                    element.PreviewDragEnter -= new System.Windows.DragEventHandler(element_PreviewDragEnter);
                    element.PreviewDragOver -= new System.Windows.DragEventHandler(element_PreviewDragEnter);
                    element.PreviewDrop -= new System.Windows.DragEventHandler(element_PreviewDrop);
                }
            }
        }

        static void element_PreviewDrop(object sender, System.Windows.DragEventArgs e)
        {
            //DataFormats.Bitmap
            DataFormat fmt = GetDragDrop(sender as TextBox);
            object text = e.Data.GetData(fmt.Name);
            TextBox tv = sender as TextBox;
            if (tv != null && text != null)
            {
                tv.Text = string.Format("{0}", ((string[])text)[0]);
            }
        }

        static void element_PreviewDragEnter(object sender, System.Windows.DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }
    }
}
